package com.cloudbroker.bcs.platform.ltb.configure.filter;

import com.cloudbroker.bcs.common.context.DataContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class DataBindFilter implements Filter {
    
    private static final Logger LOG = LoggerFactory.getLogger(DataBindFilter.class);
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOG.info(">>>>>>>>>>>>>>>>>>>>>>>" + DataBindFilter.class.getName() + " loaded");
    }
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
            ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        extractTenantIdFromUrl(httpRequest);
        try {
            chain.doFilter(request, response);
        } finally {
            DataContext.clear();
        }
    }
    
    private void extractTenantIdFromUrl(HttpServletRequest httpRequest) {
        String url = httpRequest.getRequestURI();
        String contextPath = httpRequest.getContextPath();
        if (!contextPath.isEmpty()) {
            url = url.substring(contextPath.length());
        }
        int startIdx = url.indexOf('/');
        int endIdx = -1;
        if (-1 != startIdx && -1 != (endIdx = url.indexOf('/', startIdx + 1))) {
            String tenantId = url.substring(startIdx + 1, endIdx);
            DataContext.setTenantId(tenantId);
        }
    }
    
    @Override
    public void destroy() {
        
    }
    
}
